package org.kev.transit.data;

import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import org.apache.commons.httpclient.HttpException;
import org.json.JSONException;
import org.kev.transit.TransitProvider;
import org.kev.transit.util.JsonHelper;
import org.kev.transit.util.WebHelper;
import org.kev.transit.worker.TimeTableUpdateWorker;

/**
 * Convenience definitions for NotePadProvider
 */

public final class TimeTable implements BaseColumns {

	public long createDate=0;	    	
	public String routeType=null;
	public String route=null;
	public String direction=null;
	public String time=null;
	public String stopId=null;
	public String id=null;
	public long modified;

	//public Stop stopData=null;

	public static final String TABLE_NAME="time_table";
	/**
	 * The content:// style URL for this table
	 */
	public static final  Uri CONTENT_URI = Uri.parse("content://"+TransitProvider.AUTH+"/"+TABLE_NAME);
	//public static final ContentURI ROUTE_TYPE_URI
	//= ContentURI.create("content://transit/"+TimeTable.ROUTE_TYPE);


	/**
	 * route_type
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String ROUTE_TYPE = "route_type";
	/**
	 * time_id
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String TIME_ID = "time_id";


	/**
	 * direction of route
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String DIRECTION = "direction";

	/**
	 * direction of route
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String ROUTE = "route";   

	/**
	 * 
	 * stop 
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String STOP_ID = "stop_id";   

	/**
	 * direction of route
	 * <P>Type: TEXT</P>
	 */
	public static final String TIME = "time";   

	/**
	 * The timestamp for when the note was created
	 * <P>Type: INTEGER (long)</P>
	 */
	public static final String MODIFIED = "modified";
	/**
	 * The default sort order for this table
	 */
	public static final String DEFAULT_SORT_ORDER = MODIFIED+" DESC";
	private static final String TAG = "TimeTable";

	public static final ArrayList <TimeTable> getData(Activity parent,String rType,String route, String dirId,String stop){
		Log.d(TAG,">>> getData");
		Cursor cursor = null;
		ArrayList <TimeTable> list =  new  ArrayList  <TimeTable>( );

			if( dirId==null  || route==null || rType ==null || stop==null){
				Log.e(TAG,"getData has null parms!!!"+dirId+route+rType+stop);
				return list;
			}
			String whereClause = 
				TimeTable.ROUTE_TYPE+"=? AND "+
				TimeTable.ROUTE+"=? AND "+
				TimeTable.DIRECTION+"=? AND "+
				TimeTable.STOP_ID+"=?";
			String[] args={rType,route,dirId,stop};
			
			boolean hasData=false;
		try{
			cursor = parent.managedQuery(TimeTable.CONTENT_URI, new String[] {TimeTable.TIME_ID,
					TimeTable.TIME,TimeTable.ROUTE_TYPE,TimeTable.ROUTE,TimeTable.DIRECTION,TimeTable.STOP_ID}, whereClause, args, null);
			//list = new ArrayList <TimeTable> (cursor.count() );
			while(cursor.next()){
				hasData=true;
				TimeTable timeTable=new TimeTable();
				timeTable.id=cursor.getString(0);
				timeTable.time=cursor.getString(1);
				timeTable.routeType=cursor.getString(2);
				timeTable.route=cursor.getString(3);
				timeTable.direction=cursor.getString(4);
				timeTable.stopId=cursor.getString(5);
				list.add(timeTable);
				Log.d(TAG,timeTable.toXml());
			}
			//count=cursor.count();
		}finally{
			if (cursor!=null)
				cursor.close();
		}
		if(!hasData){
			Log.d(TAG,"no data found pull from web");
			try {
				list=retrieveDataFromWeb(parent,rType,route,dirId,stop);

			} catch (Exception e) {
				Log.e(TAG,"error calling web ",e);

			}
		}
		Log.d(TAG,"<<< getData"+list);
		return list;
	}
	/**
	 * 
	 * @param parent
	 * @param rType
	 * @param route
	 * @param dir
	 * @param stop
	 * @return list of TimeTables objects
	 * @throws HttpException
	 * @throws IOException
	 * @throws JSONException
	 */
	private static ArrayList <TimeTable> retrieveDataFromWeb(Activity parent,String rType, String route,String dir,String stop) throws HttpException, IOException, JSONException{
		Log.d(TAG,"did not find any data in tables get it from the web");
		String jsonText=null;
		jsonText=WebHelper.getTimeTable(rType, route, dir, stop);
		ArrayList <TimeTable> list= new ArrayList <TimeTable>();
		list= JsonHelper.getTimeTables(jsonText);
		Log.d(TAG,"Retrieved data from web="+list.size());
		/*	for(int i=0;i<list.size();i++){
			TimeTable data = list.get(i);
			Log.d(TAG,"timetable="+data.toXml());
		}*/
		
		//cache data to DB in background
		TimeTableUpdateWorker worker=new TimeTableUpdateWorker(parent, list);
		Thread t = new Thread(worker);
		t.start();
		
		//worker.run();
		return list;
	}
	/**
	 * dumps current instance values to a string 
	 * in a XML format
	 * @return XML
	 */
	public String toXml(){
		String stopXml=null;
		return
		"<"+TABLE_NAME+">\n"+
		"\t<"+TimeTable._ID+">"+id+"</"+TimeTable._ID+">\n"+
		"\t<"+TimeTable.ROUTE+">"+route+"</"+TimeTable.ROUTE+">\n"+
		"\t<"+TimeTable.ROUTE_TYPE+">"+routeType+"</"+TimeTable.ROUTE_TYPE+">\n"+
		"\t<"+TimeTable.DIRECTION+">"+direction+"</"+TimeTable._ID+">\n"+
		"\t<"+TimeTable.STOP_ID+">"+stopId+"</"+TimeTable.STOP_ID+">\n"+
		"\t<"+TimeTable.MODIFIED+">+"+modified+"</"+TimeTable.MODIFIED+">\n"+
		stopXml+		    		 
		"</"+TABLE_NAME+">\n" ;

	}
	public String toString(){
		return time;
	}

} //End Base Columns
